import { Component, Vue, Prop, Watch, PropSync } from 'vue-property-decorator';
import * as CommonService from '@/views/common/common-service';
import AppButton from '../app-button/index.vue';
import SearchItem from './search-item/index.vue';

@Component({
  components: {
    AppButton,
    SearchItem
  }
})
export default class AppSearch extends Vue {
  @PropSync('searchWord', {
    required: false,
    default: '',
  }) _searchWord!: string;

  @Prop({
    required: false,
    default: () => [],
  }) searchList!: any[];
  
  @Prop({
    required: false,
    default: '',
  }) changeFlag!: any;
  
  @Prop({
    required: false,
    default: '.main-table',
  }) drawerContainer!: string;

  /** 生效的搜索数量 */
  activedNumber: number = 0;
  /** 是否展示高级搜索 */
  show: boolean = false;
  /** 尺寸动画 */
  renderSize: boolean = false;
  items: any[] = [
    {label: '取消', handler: () => this.setShow(false), time: 100},
    {label: '重置', style: 'blue', handler: () => this.reset(), time: 100},
    {label: '确定', style: ['fill', 'blue'], handler: () => this.onSearch(), time: 100}
  ]

  @Watch('changeFlag') 
  onFlagChange(){
    this.setShow(false);
    this.reset(true);
  }

  /** 高级搜素高度 */
  get drawerHeight() {
    const container = document.querySelector(this.drawerContainer);
    return container?.clientHeight || 0;
  }

  reset(flag: boolean = false) {
    if (flag) {
      this.activedNumber = 0;
    }
    this._searchWord = '';
    this.searchList.forEach((s: any) => {
      s.value = null;
    })
  }

  onChange(item: any, val: any = '') {
    this.searchList.forEach(v => {
      if (item.sonName === v.name && (v.api !== null || v.api !== '')) {
        let api = this.getParams(v.api, val);
        CommonService.getDate(api, null).then((data: any[]) => {
          let item = [];
          if (data.length > 1) {
            item.push({
              children: null,
              disabled: false,
              icon: null,
              isLeaf: false,
              label: '全部',
              leaf: false,
              level: 0,
              styleClass: null,
              title: null,
              value: ''
            });
          }
          data.forEach(j => {
            item.push(j);
          });
          v.items = item;
        });
      }
    });
  }

  // 动态替换参数
  getParams(url: string, param: any) {
    let result;
    let reg = /\#(.+?)\#/g;
    while ((result = reg.exec(url)) != null) {
      url = url.replace(result[0], param !== null ? param : '');
    }
    return url;
  }

  onSearch() {
    this.activedNumber = 0;
    this.searchList.forEach((item, index) => {
      if (index > 0 && item.value) {
        this.activedNumber++;
      }
    });
    this.$emit('onSearch');
  }

  setShow(show: boolean) {
    if (show) {
      this.show = true;
    } else {
      setTimeout(() => {
        this.show = false;
      }, 110);
    }
    this.renderSize = show;
    setTimeout(() => {
      this.renderSize = !show;
    }, 10);
  }
}